const app = getApp()
const _request = require("../../utils/request.js");
var timerse;
Page({
  data: {
    mallimgUrl: app.globalData.mallimgUrl,
    orderId:'',//订单id
    orderSn:'',//订单编号
    realityPayPrice:'',//支付金额
    createordertime:'',//创建订单时间
    show_time:'',//倒计时
    type:1,//1微信支付 2余额支付
    balance:0,//用户余额

    //
	isFocus: false,
	show:false,
	valArr:['','','','','',''],
    valueData: '', 
  },
  hide(){
	this.setData({
		show:false
	})
  },
    // 获得焦点时
    handleUseFocus() {
		this.setData({
		  focusType: true
		})
	  },
  
	  // 失去焦点时
	  handleUseBlur() {
		this.setData({
		  focusType: false
		})
	  },
  
	  // 点击6个框聚焦
	  handleFocus() {
		this.setData({
		  isFocus: true
		})
	  },
  
	  // 获取输入框的值
	  handleSetData(e) {
		// 更新数据
		console.log(e)
		let val = e.detail.value;
		let valArr = ['','','','','','']
		if(!isNaN(val)){

		}else{
			val=val.slice(0,val.length-1)
		}
		for(let i in val){
			valArr[i] = val[i]
		}
		console.log(valArr)
		this.setData({
		  valueData: val,
		  valArr:valArr
		})
		// 当输入框的值等于6时（发起支付等...）
		if (e.detail.value.length === 6) {
      _request.postObj('/order/balancePay', {
        orderSn: this.data.orderSn,
        payWord:this.data.valueData,
        userId: wx.getStorageSync('userId'),
        }, app.globalData.mallType).then(res=>{
          if (res.data.code === 200) {
            wx.redirectTo({
            url: '/pages/mallorder/orderinfo?orderid='+this.data.orderId,
            })
          }else{
            wx.showToast({
              title: res.data.message,
              icon:'none'
            })
          }
        }).catch(err=>{
          wx.showToast({
            title: err.data.message,
            icon:'none'
          })
        })
		  // 通知用户输入数字达到6位数可以发送接口校验密码是否正确
		  //
    // _request.postObj('/mallPay/checkPayWord', {
    //   userId: wx.getStorageSync('userId'),
    //   payWord:this.data.valueData
    // }, app.globalData.mallType).then(res=>{
		// 	if(res.data.code!==200){
    //     wx.showToast({
    //       title: res.data.message,
    //       icon:'none'
    //     })
		// 		//密码错误
		// 		this.setData({
		// 			valArr:['','','','','',''],
		// 			valueData: '', 
		// 		})
		// 	  return  Promise.reject(res.data);
		// 	}else{
		// 		//密码正确
		// 	 	return  _request.postObj('/order/balancePay', {
		// 				orderSn:this.data.orderSn,
		// 			}, app.globalData.mallType)
		// 	}
		//   }).then((res) => {
    //     if (res.data.code === 200) {
    //       wx.redirectTo({
    //       url: '/pages/mallorder/orderinfo?orderid='+this.data.orderId,
    //       })
    //     }else{
    //       wx.showToast({
    //         title: res.data.message,
    //         icon:'none'
    //       })
    //     }
		//   }).catch(err=>{
    //     wx.showToast({
    //       title: err.data.message,
    //       icon:'none'
    //       })
    //     })

		//         // 判断是否有支付密码
    //   // 判断输入的密码是否正确

		}
	  },

//   
  onLoad: function (options) {
    this.setData({
      orderId:options.orderId,
      orderSn:options.orderSn,
      realityPayPrice:options.realityPayPrice,
      createordertime:options.createordertime,
    })
    this.gettimerse()//倒计时
    this.getCashInfo()//获取用户余额
  },
  onUnload: function () {
    clearInterval(timerse)
  },
  gettimerse(){
    timerse = setInterval(() => {
      let createordertime = this.data.createordertime / 1000 + 86400 //结束待支付时间
      createordertime--;
      let now = new Date().getTime() / 1000; //当前时间换时间戳
      let diff = parseInt(createordertime - now);
      if (diff < 0) {
        clearInterval(timerse)
        wx.navigateBack({ delta: 1 })
      } else {
        let date = this.formattime(diff * 1000);
        this.setData({
          show_time: date
        })
      }
    }, 1000)
  },
  //格式化时间
  formattime(time) {//格式化时间戳
    var leave1 = time % (24 * 3600 * 1000) //计算小时    
    var hour = Math.floor(leave1 / (3600 * 1000))
    var leave2 = leave1 % (3600 * 1000) //计算分钟    
    var minute = Math.floor(leave2 / (60 * 1000))
    var leave3 = leave2 % (60 * 1000) //计算秒    
    var second = Math.round(leave3 / 1000) == '60' ? '00' : Math.round(leave3 / 1000)
    return [hour, minute, second].map(this.formatNumber).join(':')
  },
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  // 获取用户余额
  getCashInfo(e){
    _request.get('/mallPay/getCashInfo', {
      id: wx.getStorageSync('userId'),
    }, app.globalData.mallType).then((res) => {
      if (res.data.code === 200) {
        this.setData({
          balance: res.data.data.balance
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon:'none'
        })
      }
    })
  },
  // 选择支付类型
  oddcheckbox(e){
    this.setData({
      type:e.currentTarget.dataset.index
    })
  },
  // 调起支付
  handlepay: function() {
    if(this.data.type==1){
      // 微信支付
      var that = this
      wx.login({
        success: res => {
          var _code = res.code
          // 1用户2理发师3门店
          _request.postObj('/order/prepay', {
            orderId:that.data.orderId,
            client:3,
            code:_code,
          }, app.globalData.mallType).then((res) => {
            console.log(res)
            if (res.data.code === 200) {
              that.getrequestPayment(res.data.data)//微信支付
            }else{
              wx.showToast({
                title: res.data.message,
                icon:'none'
              })
            }
          })
        }
      })
    }else{

      // 余额支付
      // if(this.data.balance<=0 || !this.data.balance || this.data.realityPayPrice>=this.data.balance-0.01){
      //   wx.showToast({
      //     title: '余额不足',
      //     icon:'none'
      //   })
      //   return;
      // }
      _request.get('/mallPay/initPayWord', {
        userId: wx.getStorageSync('userId'),
      }, app.globalData.mallType).then(res=>{
        console.log(res)
        if(res.data.data===1){
          //设置了密码
          this.setData({
            show:true
          })
        }else{
          wx.showModal({
            title: '您还未设置密码',
            content: '请先设置密码',
            confirmText: '前往设置',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/setpaypassword/index',
                })
              } else if (res.cancel) {}
            }
          })
          // return  Promise.reject();
        }
      }).catch(err=>{
        wx.showToast({
          title: err.message,
          icon:'none'
        })
      })
    }
  },
  // 调起支付
  getrequestPayment(e){
    var that = this
    wx.requestPayment({
      'timeStamp': e.timestamp,
      'nonceStr': e.nonceStr,
      'package': e.pkg,
      'signType': e.signType,
      'paySign': e.sign,
      'success': function (r) {
        wx.redirectTo({
          url: '/pages/mallorder/orderinfo?orderid='+that.data.orderId,
        })
        console.log('成功')
        console.log(r)
      },
      'fail': function (r) {
        console.log('失败')
        console.log(r)
      },
      'complete': function (r) {
        console.log('1111')
        console.log(r)
      }
    })
  },
})